<template>
  <div>
    <!-- 文章列表 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" success-text="刷新成功">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        offset="50"
      >
        <!-- 文章列表 -->
        <article-item
          v-for="(item,index) in articleList"
          :key="index"
          :obj="item"
          @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
        ></article-item>
      </van-list>
    </van-pull-refresh>

  </div>
</template>

<script>
import { articlesListAPI } from '@/api'
import { timeAgo } from '../../utils/date'

import ArticleItem from './components/ArticleItem.vue'
export default {
  props: {
    cid: Number
  },
  components: {
    ArticleItem
  },
  data () {
    return {
      articleList: [],
      finished: false,
      loading: false,
      nextTimestamp: null,
      isLoading: false
    }
  },
  methods: {
    async getArticleList () {
      // 负责拿文章列表数据
      const res = await articlesListAPI({
        channelId: this.cid,
        timestamp: this.nextTimestamp
      })
      console.log(res)
      // 回来的数据进行预处理, 把时间转成多久多久之前
      res.data.data.results.forEach((obj) => {
        obj.pubdate = timeAgo(obj.pubdate)
      })
      // 如果无数据
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
        this.articleList = [...this.articleList, ...res.data.data.results]
        // 等待网络请求结果后
        this.loading = false // 底部加载更多状态
      }
    },
    onLoad () {
    // 有第一页数据以后, onLoad再发请求
      if (this.articleList.length > 0) {
        this.getArticleList()
      }
    },
    onRefresh () {
      this.nextTime = null
      this.articleList = []
      this.getArticleList()
      this.isLoading = false
    }
  },
  async created () {
    this.getArticleList()
  }
}
</script>
